package online.xuping.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 类描述:    .
 *
 * @author xuping
 * 创建时间:  [2023/10/30 16:40]
 */
@Slf4j
public class MinioUtil {
    private String host;
    private String ak;
    private String sk;

    private String bucket;
    private MinioClient minioClient;

    @SneakyThrows
    public   MinioUtil(String host,String ak, String sk,String bucket) {
        this.bucket = bucket;
        this.ak = ak;
        this.host = host;
        this.sk = sk;
        minioClient =
                MinioClient.builder()
                        .endpoint(host)
                        .credentials(ak, sk)
                        .build();
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        } else {
            log.info("Bucket '{}' already exists.",bucket);
        }
    }

    /**
     * 保存
     * @param path
     * @param targetPath
     */
    @SneakyThrows
    public void save(String path, String targetPath) {
        minioClient.uploadObject(
                UploadObjectArgs.builder()
                        .bucket(bucket)
                        .object(targetPath)
                        .filename(path)
                        .build());
    }

}
